from decimal import Decimal
from typing import Any

from django_redis import get_redis_connection
from ninja_extra import api_controller, route
from ninja_jwt.authentication import JWTAuth

from meiduo_mall.base.schemas import Message
from .schemas import OrderSchemaOut, OrderCommitSchema, OrderCommitSchemaOut

from goods.models import SKU


@api_controller(tags=['订单模块'], auth=JWTAuth())
class CountOrderAPI:
    @route.get('orders/settlement/', summary='去结算', response={200: OrderSchemaOut})
    def get(self):
        redis_conn = get_redis_connection('cart')
        # 获取用户
        user = self.context.request.user

        # 获取redis购物车数据
        cart_dict_redis = redis_conn.hgetall(f'cart_{user.id}')
        selected_ids = redis_conn.smembers(f'selected_{user.id}')

        # 接收redis中的购物车数据
        cart_dict = {}
        # redis中勾选的商品组成字典
        for sku_id_bytes in selected_ids:
            cart_dict[int(sku_id_bytes)] = int(cart_dict_redis[sku_id_bytes])

        # 获取勾选商品的模型数据
        skus = SKU.objects.filter(id__in=cart_dict.keys())
        for sku in skus:
            sku.count = cart_dict[sku.id]
            sku.selected = True
        # 运费
        freight = Decimal('10.00')

        return {'freight': freight, 'skus': skus}

    @route.post('orders/', summary='确认订单', response={200: OrderCommitSchemaOut, 400: Message})
    def commit_order(self, data: OrderCommitSchema):
        try:
            obj = data.create()
            return obj
        except Exception as e:
            return 400, {'msg': f'{e}'}
